﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Dora.Orm.SqlSugarCore
{

    public static class SugarExtension
    {

        public static string SumTotalToJson<TResult, T>(this ISugarQueryable<T> query, params Expression<Func<T, TResult>>[] expressions)
        {
            var memberNames = expressions.Select(x =>
            {
                var body = x.Body;
                if (!(body is MemberExpression))
                    return "";

                var memberName = ((MemberExpression)body).Member.Name;
                return memberName;
            }).Where(x => !string.IsNullOrEmpty(x));
            if (!memberNames.Any()) return "";
            var sumFormatList = memberNames.Select(memberName => $"SUM({memberName}) AS {memberName},");
            var selectSumSql = string.Join("", sumFormatList).TrimEnd(',');
            return query.Select(selectSumSql).ToJson();




        }

        public static Object SumTotalToEntity<TResult, T>(this ISugarQueryable<T> query, params Expression<Func<T, TResult>>[] expressions)
        {
            var memberNames = expressions.Select(expr =>
            {
                var rtn = "";
                Console.WriteLine(expr);

                try
                {
                    if (expr.Body is UnaryExpression)
                    {
                        rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
                    }
                    else if (expr.Body is MemberExpression)
                    {
                        rtn = ((MemberExpression)expr.Body).Member.Name;
                    }
                    else if (expr.Body is ParameterExpression)
                    {
                        rtn = ((ParameterExpression)expr.Body).Type.Name;
                    }
                    return rtn;
                }
                catch (Exception ex)
                {

                    throw;
                }
               
            }).Where(x => !string.IsNullOrEmpty(x));
            if (!memberNames.Any()) return default;
            var sumFormatList = memberNames.Select(memberName => $"SUM({memberName}) AS {memberName},");
            var selectSumSql = string.Join("", sumFormatList).TrimEnd(',');
            Console.WriteLine("sql语句是" + selectSumSql);
            var list = new List<int>();
            return query.Select<Object>(selectSumSql).Single();

        }








    }
}
